package com.example.demo.common.configs;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {

    private final static String AJAX = "XMLHttpRequest";
    private final static String LOGINPATH = "/login";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HttpSession session = request.getSession();

        String header = request.getHeader("X-Requested-With");
        boolean isAjax = AJAX.equals(header) ? true:false;
        if (isAjax && session.getAttribute("loginUser") == null){

            response.setHeader("REDIRECT", "REDIRECT");
            response.setHeader("CONTEXTPATH", LOGINPATH);
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);

            return false;
        }else {
            return true;
        }
    }


}
